﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace NatNetClient
{
    public class UDPSender
    {
        private readonly UdpClient _UDPClient;

        public UDPSender(string IP, int port)
        {
            //controllo che l'argomento Ip sia un indirizzo Ip valido, che non sia null o
            //una stringa vuota
            if (IP == null | String.IsNullOrEmpty(IP))
            {
                throw new ArgumentException("Invalid IP address");
            }
            try
            {
                IPAddress address = IPAddress.Parse(IP);
            }
            catch (FormatException fe)
            {
                Console.WriteLine(fe.StackTrace);
            }
            //controllo che la porta non sia una Well-Known Port
            if (port < 1024 || port > 65535)
            {
                throw new ArgumentException("Number of port invalid");
            }
            //creo il Client UDP
            _UDPClient = new UdpClient(IP, port);
            _UDPClient.DontFragment = true;
        }

        public void Send(IPacket packet, MyClientNatNet.SENDMODE mode)
        {
            if (packet == null)
                throw new ArgumentNullException("packet is null");
            OptiTrackPacket pack = (OptiTrackPacket) packet;

            byte[] bytes = new byte[0];
            switch (mode)
            {
                case MyClientNatNet.SENDMODE.STRING:
                    bytes = Encoding.Default.GetBytes(packet.ToString());
                    break;
                case MyClientNatNet.SENDMODE.BINARY:
                    bytes = pack.ToBinary();
                    break;
                case MyClientNatNet.SENDMODE.MAVLINK:
                    bytes = pack.ToMavlink();
                    break;
            }

            byte[] tosend = new byte[1460];
            //byte[] tosend = new byte[1024];
            //prova con windows XP vero: FUNZIONA!
            //byte[] tosend = new byte[100];
            //byte[] tosend = new byte[1000];
            //byte[] tosend = new byte[bytes.Length];
            Array.Copy(bytes, tosend, bytes.Length);
            try
            {
                //_UDPClient.Send(bytes, bytes.Length);
                _UDPClient.Send(tosend, tosend.Length);
            }
            catch (SocketException skEx)
            {
                Console.WriteLine(skEx.StackTrace);
            }
        }

        public void Close()
        {
            _UDPClient.Close();
        }


    }
}
